package com.gx.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.gx.security.CSRFTokenManager;

public class CommonInterceptor extends HandlerInterceptorAdapter {
	private static Logger log = Logger.getLogger(CommonInterceptor.class);

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		boolean result = false;
		String username = (String) request.getSession().getAttribute("username");
		System.out.println(request.getParameter("csrf"));
		// 验证CSRFToken
		if (request.getParameter("csrf") == null) {
			// 判断
			if (request.getHeader("__RequestVerificationToken") == null
					|| request.getSession().getAttribute(CSRFTokenManager.CSRF_TOKEN_FOR_SESSION_ATTR_NAME) == null
					|| !request.getHeader("__RequestVerificationToken").equals(request.getSession()
							.getAttribute(CSRFTokenManager.CSRF_TOKEN_FOR_SESSION_ATTR_NAME).toString())) {
				log.info("验证未通过");
				request.getRequestDispatcher("/login/login.jsp").forward(request, response);
				return result;
			} else {
				log.info("验证通过");
				if (username == null) {
					request.getRequestDispatcher("/login/login.jsp").forward(request, response);
					return result;
				} else {
					result = true;
				}
			}
		} else if (request.getParameter("csrf").equals(
				request.getSession().getAttribute(CSRFTokenManager.CSRF_TOKEN_FOR_SESSION_ATTR_NAME).toString())) {
			// 通过
			log.info("验证通过");
			if (username == null) {
				request.getRequestDispatcher("/login/login.jsp").forward(request, response);
				return result;
			} else {
				result = true;
			}
		}
		return result;
	}

	/**
	 * 在业务处理器处理请求执行完成后,生成视图之前执行的动作
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等
	 * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
